<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>借货订单记录</title>
    <script type="text/javascript">
      var newLoanWin;
      var editLoanWin;
      var editLoanAfterAuditWin
      var loanOrderId;
      var deliveryForLoanWin;
      var loanOrderDS;
      Ext.onReady(function(){
        
        var customer = Ext.create('Ext.form.ComboBox', {
          fieldLabel: '客户',
          store: customerAllInfoStore,
          allowBlank: false,
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'customer_id',
          loadingText: '搜索中...',
          minChars: 0,
          anchor: '100%',
          listConfig: {
            loadingText: 'Searching...',
            getInnerTpl: function() {
              return '<div style="float:left; width:70px">{number}</div><div style="float:left;width:230px">|{name}</div>| {phone}';
            }
          },
          pageSize: 10
        });
               
        var orderNumber = Ext.create('Ext.form.field.Text', {
          fieldLabel: '单号',
          name: 'order_number',
          anchor: '100%'
        });
        
        var auditingStatus = Ext.create('Ext.form.ComboBox', {
          fieldLabel: '审批状态',
          store: auditStatusStore,
          displayField:'text',
          typeAhead: true,
          queryMode: 'local',
          name: 'auditing_status',
          editable:false,
          valueField: 'value',
          anchor: '100%'
        });

        var beginDate = Ext.create('Ext.form.field.Date', {
          fieldLabel: '发货日期',
          name: 'begin_date',
          id: 'begin_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-01",          
          anchor: '95%',
          vtype: 'daterange',
          endDateField: 'end_date',
          anchor: '100%'
        });
        var endDate = Ext.create('Ext.form.field.Date', {
          fieldLabel: '至',
          name: 'end_date',
          id: 'end_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-01",          
          anchor: '95%',
          vtype: 'daterange',
          startDateField: 'begin_date',
          anchor: '100%'
        });

        //产品
        var productCBB = Ext.create('Ext.form.ComboBox', {
          store: productStore,
          fieldLabel: '产品',
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'product_id',
          loadingText: '搜索中...',
          anchor: '100%',
          pageSize: 10,
          minChars: 0,
          listConfig: {
            loadingText: 'Searching...',
            getInnerTpl: function() {
              return '<div style="float:left; width:220px">{name}</div><div style="float:left; width:120px">{number}</div>{is_suit}';
            }
          }
        });
        
        //借货员
        var employeeCBB = Ext.create('Ext.form.ComboBox', {
          store: employeeStore,
          fieldLabel: '借货员',
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          name: 'employee_id',
          loadingText: '搜索中...',
          anchor: '100%',
          //pageSize: 10,
          minChars: 0
        });

        //
        var department = Ext.create('Ext.form.ComboBox', {
          store: departmentStore,
          fieldLabel: '公司部门',
          allowBlank: false,
          blankText: "部门必须选择",
          valueField: 'id',
          displayField: 'name',
          name: 'department_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',          
          loadingText: '搜索中...',
          anchor: '100%',
          //pageSize: 10,
          readOnly:false,
          minChars: 0
        });
        
        var searchButton = Ext.create('Ext.Button', {
          text: '搜索',
          iconCls: 'finding',
          width:70,
          handler: function(){
            loanOrderDS.removeAll();
            /*loanOrderDS.getProxy().extraParams.order_number = orderNumber.getValue();
            loanOrderDS.getProxy().extraParams.auditing_status = auditingStatus.getValue();
            loanOrderDS.getProxy().extraParams.sales_id = employeeCBB.getValue();
            loanOrderDS.getProxy().extraParams.product_id = productCBB.getValue();
            loanOrderDS.getProxy().extraParams.begin_date = beginDate.getRawValue();
            loanOrderDS.getProxy().extraParams.end_date = endDate.getRawValue();
            loanOrderDS.getProxy().extraParams.customer_id = customer.getValue();
            loanOrderDS.getProxy().extraParams.department_id = department.getValue();
            loanOrderDS.getProxy().extraParams.sales_id = employeeCBB.getRawValue();
            loanOrderDS.getProxy().extraParams.start = 0;
            loanOrderDS.load();*/
            
            loanOrderDS.getProxy().extraParams = queryFormPanel.getForm().getFieldValues();
            toolBar.moveFirst();        
          }
        });

        var clearButton = Ext.create('Ext.Button', {
          text: '清空',
          width:50,
          handler: function(){
            queryFormPanel.form.reset();
          }
        });

        var queryFormPanel = Ext.create('Ext.form.Panel', {
          fieldDefaults: {
            labelWidth: 60,
            labelAlign: 'right'
          },
          width: screenWidth-165,
          frame : true,
          border:false,
          items: [{
              xtype: 'fieldset',
              defaults: {width: screenWidth-190},
              title: '查询条件',
              border: true,
              items: [{
                  layout: 'column',
                  xtype: 'container',
                  items: [{
                      columnWidth: .13,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [orderNumber]
                    }, {
                      columnWidth: .13,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [auditingStatus]
                    }, {
                      columnWidth: .33,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [customer]
                    },{
                      columnWidth: .15,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [employeeCBB]
                    }, {
                      columnWidth: .11,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [searchButton]
                    }]
                },{
                  layout: 'column',
                  xtype: 'container',
                  items: [{
                      columnWidth: .13,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [beginDate]
                    }, {
                      columnWidth: .13,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [endDate]
                    }, {
                      columnWidth: .33,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [productCBB]
                    }, {
                      columnWidth: .15,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [department]
                    }, {
                      columnWidth: .11,
                      layout: 'anchor',
                      xtype: 'container',
                      items: [clearButton]
                    }]
                }]
            }]
        });

        //显示借货订单操作时的窗口介面。
        //----------------------------------借货订单Grid-------------------------       

        loanOrderDS = Ext.create('Ext.data.Store', {
          //autoDestroy : true,
          model : 'LoanOrderModel',
          proxy : {
            type : 'ajax',
            url : '/loan/getAllLoans',
            reader : {
              type : 'json',
              root : 'root',
              totalProperty : 'totalProperty'// 数据集记录总数
            }
          },
          pageSize : pageSize,
          autoLoad : true
        });
        
        
        var toolBar = Ext.create('Ext.toolbar.Paging', {
          pageSize: pageSize,
          store: loanOrderDS,
          displayInfo: true,
          displayMsg: "显示第 {0} 条到 {1} 条记录，一共 {2} 条",
          emptyMsg: "没有记录",
          items:["-",{
              text: '新增',
              iconCls: 'addItem',
              handler : function(){
                newLoanWin = Ext.create('Ext.window.Window', {
                  layout: 'fit',
                  width: 1067,
                  height: 485,
                  closeAction: 'destroy',
                  plain: true,
                  modal: true,
                  constrain:true,
                  //modal: true,
                  title: '新增借货订单',
                  autoLoad: {
                    url: "/loan/newLoan",
                    scripts: true
                  }
                });
                newLoanWin.on("destroy",function(){
                  loanOrderDS.load();
                });
                newLoanWin.resizable = false;
                newLoanWin.show();
              }
            },"-",{
              text: '编辑',
              iconCls: 'editItem',
              handler : function(){
                var records = loanOrderGrid.getSelectionModel().getSelection();
                if(records.length==0){
                  Ext.MessageBox.show({
                    title: '提示信息',
                    msg: "请先选中一条记录后，再编辑。",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                }else{
                  loanOrderId = records[0].get('id');
                  if(records[0].get('auditing_status').indexOf('申请') < 0 && records[0].get('auditing_status')==''){
                    editLoanWin = Ext.create('Ext.window.Window', {
                      layout: 'fit',
                      width: 1067,
                      height: 485,
                      closeAction: 'destroy',
                      plain: true,
                      modal: true,
                      constrain:true,
                      //modal: true,
                      title: '编辑借货订单',
                      autoLoad: {
                        url: "/loan/editLoan?id="+loanOrderId,
                        scripts: true,
                        callback: function(options, success, response, request)
                        {
                          if (response.responseText === "NoPrivilege"){
                            editLoanWin.close();
                          }
                        }
                      }
                    });
                    editLoanWin.on("destroy",function(){
                      loanOrderDS.load();
                    });
                    editLoanWin.resizable = false;
                    editLoanWin.show();
                  }else if (records[0].get('auditing_status').indexOf('申请') > -1 || records[0].get('auditing_status') == '通过撤消'){
                    Ext.MessageBox.alert('提示信息','正在申请、已经撤消的借货订单，不能编辑。');
                  }else if(records[0].get('auditing_status') == '通过新增' || records[0].get('auditing_status') == '通过变更' || records[0].get('auditing_status') == '驳回变更'){
                    Ext.MessageBox.confirm('警告',"通过审批的'新增'或'更新'的借货订单在编辑后，要从新通过审批，你确认要编辑此订单吗？",function (button){
                      if(button=='yes'){
                        editLoanAfterAuditWin = Ext.create('Ext.window.Window', {
                          layout: 'fit',
                          width: 967,
                          height: 475,
                          closeAction: 'destroy',
                          plain: true,
                          modal: true,
                          constrain:true,
                          //modal: true,
                          title: '审批后，调整借货订单',
                          autoLoad: {
                            url: "/loan/editLoanAfterAudit?id="+loanOrderId,
                            scripts: true,
                            callback: function(options, success, response, request)
                            {
                              if (response.responseText === "NoPrivilege"){
                                editLoanAfterAuditWin.close();
                              }
                            }
                          }
                        });
                        editLoanAfterAuditWin.on("destroy",function(){
                          loanOrderDS.load();
                        });
                        editLoanAfterAuditWin.resizable = false;
                        editLoanAfterAuditWin.show();
                      }
                    });
                  }
                }
              }
            },'-',{
              text: '撤消',
              iconCls: 'cancel',
              handler : function(){
                var records = loanOrderGrid.getSelectionModel().getSelection();
                if (records.length == 0) {
                  return false;
                }else{
                  if(records[0].get('deal_with_status') != '已撤消' && records[0].get('auditing_status').indexOf('申请') < 0 ){
                    var orderNumber = records[0].get('order_number')
                    loanOrderId = records[0].get('id');
                    Ext.MessageBox.confirm("提示","你确认要申请撤消订单号为： \""+orderNumber+"\" 的借货订单吗？",function(btn){
                      if(btn=="yes"){
                        Ext.Ajax.request({
                          url : '/loan/applyToCancel?id=' + loanOrderId,
                          success : function (result, request) {
                            loanOrderDS.load();
                          },
                          failure : function (result, request){
                            Ext.MessageBox.show({
                              title: '消息',
                              msg: "通讯失败，请从新操作",
                              buttons: Ext.MessageBox.OK,
                              icon: Ext.MessageBox.WARNING
                            });
                          },
                          method : 'GET'
                        });
                      }else{
                        //alert("no");
                      }
                    });
                  }else{
                    Ext.MessageBox.alert('提示信息','已经撤消或正于申请状态的各类订单，不能撤消。');
                  }
                }
              }
            },'-',{
              text: '打印借货凭据',
              iconCls: 'print',
              handler : function(){
                var records = loanOrderGrid.getSelectionModel().getSelection();
                if (records.length == 0) {
                  return false;
                }else{
                  this.disable();
                  loanId = records[0].get('id');
                  //LODOP.SET_PRINT_PAGESIZE(1,0,0,'A5')
                  LODOP.PRINT_INIT("");
                  LODOP.SET_PRINT_PAGESIZE(1,"210mm","148mm","")
                  //LODOP.SET_PRINT_PAGESIZE(1,"148mm","210mm","")
                  LODOP.ADD_PRINT_URL(30,'5%',"90%","100%",'http://'+window.location.host+'/loan/loan_print_header?id='+loanId);
                  LODOP.SET_PRINT_STYLEA(0,"ItemType",1);
                  LODOP.ADD_PRINT_TBURL(170,'5%',"90%","43%",'http://'+window.location.host+'/loan/loan_print_content?id='+loanId);
                  LODOP.SET_PRINT_STYLEA(0,"ItemType",4);
                  LODOP.ADD_PRINT_URL(425,'5%',"90%","100%",'http://'+window.location.host+'/loan/loan_print_footer?id='+loanId);
                  LODOP.SET_PRINT_STYLEA(0,"ItemType",1);
                  LODOP.ADD_PRINT_TEXT(495,'15%',"80%","8%","第一联：成本（白） 第二联：财务（绿） 第三联：提货（粉） 第四联：客户（黄） 第五联：销售（兰）");
                  LODOP.SET_PRINT_STYLEA(0,"ItemType",1);
                  LODOP.ADD_PRINT_TEXT(515,'35%',"90%","8%","页号：第#页/共&页 打印日期："+getDate());
                  LODOP.SET_PRINT_STYLEA(0,"ItemType",2);
                  LODOP.PREVIEW();
                  this.enable();
                }
              }
            }]
        })
        
        
        //生成要订单的产品的Grid
        var loanOrderGrid = Ext.create('Ext.grid.Panel', {
          title:'借货订单列表',
          store: loanOrderDS,
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: 'DB',
              dataIndex: 'id',
              width: 50
            },{
              header: '借货订单单号',
              dataIndex: 'order_number',
              width: 170
            },{
              header: '客户',
              dataIndex: 'customer_name',
              width: 190
            },{
              header: '发货日期',
              dataIndex: 'action_date',
              renderer: Ext.util.Format.dateRenderer('Y-m-d'),
              width: 80
            },{
              header: '借货员',
              dataIndex: 'sales_name',
              width: 55
            },{
              header: '操作员',
              dataIndex: 'employee_name',
              width: 55
            },{
              header: '部门',
              dataIndex: 'department_name',
              width: 70
            },{
              header: '审批状态',
              dataIndex: 'auditing_status',
              width: 65,
              renderer: auditingStatusRender
            },{
              header: '审批者',
              dataIndex: 'auditor_name',
              width: 55
            },{
              header: '审批意见',
              dataIndex: 'audit_opinion',
              width: 150
            },{
              header: '处理状态',
              dataIndex: 'deal_with_status',
              renderer: dealWithStatusRender,
              width: 70
            },{
              header: '出库状态',
              dataIndex: 'store_status',
              renderer: dealWithStatusRender,
              width: 70
            },{
              header: '返库状态',
              dataIndex: 'return_status',
              renderer: dealWithStatusRender,
              width: 70
            },{
              header: '借货类型',
              dataIndex: 'sub_type',
              width: 70
            },{
              header: '备注',
              dataIndex: 'description',
              width: 130
            },{
              header: '生成日期',
              dataIndex: 'created_at',
              renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
              width: 100
            },{
              header: '修改日期',
              dataIndex: 'updated_at',
              renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
              width: 100
            }],
          selModel :Ext.create('Ext.selection.CheckboxModel'),
          loadMask: true,
          //renderTo: 'order_sale_list_grid',
          width: screenWidth-165,
          height: 315,
          frame: true,
          //title: '进货品种列表',
          //plain:true,
          //plugins: checkColumn,
          tbar: toolBar
        });
        
        loanOrderGrid.on('itemdblclick', function(gridPanel, record,item,index,e,options){
          loanOrderId = loanOrderDS.getAt(index).get('id');
          var loanOrderNumber = loanOrderDS.getAt(index).get('order_number');
          //loanOrderDS.load();
          loanOrderDetailDS.removeAll();
          loanOrderDetailDS.load({params:{'loan_id': loanOrderId}});
          loanOrderDetailGrid.setTitle("借货订单："+loanOrderNumber+"，的详细信息");
        });

        loanOrderGrid.on('itemcontextmenu', function(grid, record,item,index,e,options){
          //初始化所有右键菜单为不可用
          loanOrderId = loanOrderDS.getAt(index).get('id');
          currentOrderNumber = loanOrderDS.getAt(index).get('order_number');
          var auditingStatus = loanOrderDS.getAt(index).get('auditing_status');
          e.preventDefault();
          rightClick.showAt(e.getXY());
        });
        
        //############ 订单-右键菜单 ##########
        var deliveryForLoanItem = Ext.create('Ext.menu.Item', {
          text: '【相关出库单信息】',
          //iconCls: 'album',
          handler: rightMenuDeliveryForLoanFn
        });

        function rightMenuDeliveryForLoanFn(){
          deliveryForLoanWin = Ext.create('Ext.window.Window', {
            layout: 'fit',
            width:998,
            height: 600,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            draggable: false,
            //modal: true,
            title: '借货订单\"'+currentOrderNumber+'\"相关的出库单信息',
            autoLoad: {
              url: "/loan/deliveryForLoanList?id="+loanOrderId,
              scripts: true
            }
          });
          deliveryForLoanWin.on("destroy",function(){
            loanOrderDS.load();
          });
          deliveryForLoanWin.resizable = false;
          deliveryForLoanWin.show();
        }


        var loanOrderHxItem = Ext.create('Ext.menu.Item', {
          text: '【变更历史】',
          //iconCls: 'album',
          handler: rightMenuloanOrderHxFn
        });

        function rightMenuloanOrderHxFn(){
          loanOrderHxWin = Ext.create('Ext.window.Window', {
            layout: 'fit',
            width: 960,
            height: 550,
            closeAction: 'destroy',
            plain: true,
            modal: true,
            constrain:true,
            draggable: false,
            //modal: true,
            title: '借货订单：\"'+currentOrderNumber+'\"的变更记录',
            autoLoad: {
              url: "/loan/hxListForLoan?id="+loanOrderId,
              scripts: true
            }
          });
          loanOrderHxWin.on("destroy",function(){
            loanOrderDS.load();
          });
          loanOrderHxWin.resizable = false;
          loanOrderHxWin.show();
        }

        var rightClick = Ext.create('Ext.menu.Menu', {
          items: [deliveryForLoanItem,'-',loanOrderHxItem]
        });

        //--------------------------借货订单详细，双击后可显示数据----------------
        //借货订单Grid Store Detail
        var loanOrderDetailDS = Ext.create('Ext.data.Store', {
          //autoDestroy : true,
          model : 'LoanOrderDetailModel',
          proxy : {
            type : 'ajax',
            url : '/loan/getLoanDetailsBalanceById',
            reader : {
              type : 'json',
              root : 'root',
              totalProperty : 'totalProperty'// 数据集记录总数
            }
          }
        });
        
        //生成要订单的产品的Grid
        var loanOrderDetailGrid = Ext.create('Ext.grid.Panel', {
          title:'订单详细列表',
          store: loanOrderDetailDS,
          columns : [Ext.create('Ext.grid.RowNumberer'),{
              header: 'DB',
              dataIndex: 'id',
              width: 60
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              width: 270
            },{
              header: '编号',dataIndex: 'product_number',width: 100
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 70
            },{
              header: '数量',
              dataIndex: 'quantity',
              align: 'right',
              width: 60
            },{
              header: '套装或单品',
              dataIndex: 'is_suit',
              width: 70
            },{
              header: '出库差比',
              dataIndex: 'balance_quantity',
              align: 'right',
              width: 80
            },{
              header: '备注',
              dataIndex: 'description',
              width: 380
            }],
          loadMask: true,
          width: screenWidth-165,
          height: dgHeight,
          frame: true
          //title: '进货品种列表',
          //plain:true,
          //plugins: checkColumn,
        });

        //总的panel
        var workbenchPanel = Ext.create('Ext.form.Panel', {
          width: screenWidth-165,
          height: totalHeight,autoScroll:true,
          frame:false,
          layout: {type: 'table',columns:1},
          items:[queryFormPanel,loanOrderGrid,loanOrderDetailGrid]
        });
        workbenchPanel.render("order_sale_list_workbench");

      })
    </script>
  </head>
  <body>
    <div id="order_sale_list_workbench"></div>
  </body>
</html>